import { _decorator, Component, Node, find, UITransform, Vec3 } from 'cc';
const { ccclass } = _decorator;
import { Monster } from './Monster';
import { Boss } from './Boss';

@ccclass('MagicBall')
export class MagicBall extends Component {
    target: Node = null
    speed: number = 10
    canvasWidth: number = 0
    canvasHeight: number = 0

    start() {
        this.canvasWidth = find('Canvas').getComponent(UITransform).width
        this.canvasHeight = find('Canvas').getComponent(UITransform).height
    }

    /** 
     * @zh
     * 设置要被攻击的目标节点。
    */
    setTarget(target: Node) {
        this.target = target
    }

    /** 
     * @zh
     * 攻击目标节点。
    */
    attackTarget() {
        let dir = new Vec3(this.node.position).subtract(new Vec3(this.target.position)).normalize()
        this.node.setPosition(new Vec3(this.node.position).subtract3f(dir.x * this.speed, dir.y * this.speed, 0))

        // 碰撞执行逻辑
        if (this.node.getComponent(UITransform).getBoundingBox().intersects(this.target.getComponent(UITransform).getBoundingBox())) {
            let damageValue = Math.round(Math.random() * 10 + 10)

            if (this.target.name == 'monster' && !this.target.getComponent(Monster).isDead) {
                this.target.getComponent(Monster).reduceLife(damageValue)
            }
            else if (this.target.name == 'Boss' && !this.target.getComponent(Boss).isDead) {
                this.target.getComponent(Boss).reduceLife(damageValue)
            }

            this.target = null
            this.node.destroy()
        }

        // 移到屏幕外的话消失
        else if (this.node.position.x > this.canvasWidth/2+200 || this.node.position.x < -this.canvasWidth/2-200 ||
                 this.node.position.y > this.canvasHeight/2+200 || this.node.position.y < -this.canvasHeight/2-200) {
            this.target = null
            this.node.destroy()
        }
    }

    update(deltaTime: number) {
        if (this.target) {
            this.attackTarget()
        }
    }
}


